package com.histone.lib_download.contract;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

/**
 * 文件下载信息
 *
 * @author robin 2023-04-14
 */
public class DownloadTakeNotes {
    private static DownloadTakeNotes dtn;

    public static DownloadTakeNotes getInstance() {
        if (dtn == null) dtn = new DownloadTakeNotes();
        return dtn;
    }

    /**
     * 当前/未完成 的下载地址
     */
    public String downloadUrl;
    /**
     * 文件名称
     */
    public String fileName;
    /**
     * 文件目录
     */
    public String filePath;
    /**
     * 文件大小
     */
    public long fileLength;
    /**
     * 已完成下载长度
     */
    public long downloadLength;

    private SharedPreferences.Editor mEditor;

    /**
     * @return boolean 是否存在未完成的下载
     */
    public boolean initShared(Context context) {
        SharedPreferences sp = context.getSharedPreferences("DownloadTakeNotes", Context.MODE_PRIVATE);
        mEditor = sp.edit();
        downloadUrl = sp.getString("downloadUrl", "");
        fileName = sp.getString("fileName", "");
        filePath = sp.getString("filePath", "");
        fileLength = sp.getLong("fileLength", 0);
        downloadLength = sp.getLong("downloadLength", 0);
        return !TextUtils.isEmpty(downloadUrl) && !TextUtils.isEmpty(fileName) && !TextUtils.isEmpty(filePath);
    }

    public void save(String downloadUrl, String fileName, String filePath, long fileLength, long downloadLength) {
        this.downloadUrl = downloadUrl;
        this.fileName = fileName;
        this.filePath = filePath;
        this.fileLength = fileLength;
        this.downloadLength = downloadLength;
        if (mEditor == null) {
            Log.e("DownloadTakeNotes", "mEditor == null");
            return;
        }
        mEditor.putString("downloadUrl", downloadUrl);
        mEditor.putString("fileName", fileName);
        mEditor.putString("filePath", filePath);
        mEditor.putLong("fileLength", fileLength);
        mEditor.putLong("downloadLength", downloadLength);
        mEditor.commit();
    }

    public void update(long fileLength, long downloadLength) {
        if (mEditor == null) {
            Log.e("DownloadTakeNotes", "mEditor == null");
            return;
        }
        mEditor.putLong("fileLength", fileLength);
        mEditor.putLong("downloadLength", downloadLength);
        mEditor.commit();
    }

    /**
     * 下载完成清理
     */
    public void clean() {
        if (mEditor == null) {
            Log.e("DownloadTakeNotes", "mEditor == null");
            return;
        }
        mEditor.clear().commit();
    }

}
